﻿import 'dart:async';
import 'dart:developer' as developer;
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import '../../../core/controllers/ring_controller.dart';
import '../../../core/repository/default_api.dart';
import '../../../services/device_sn_manager.dart';
import '../../../core/models/heart_rate_model.dart' as api_models;
import '../../../core/models/heart_rate_api_data.dart';
import '../calendar/simple_calendar_view.dart';

/// 时间范围枚举
enum TimeRange {
  day,
  week,
  month,
}

/// 心率测量结果模型
class HeartRateMeasurementResult {
  final int heartRate;
  final DateTime measurementTime;
  final String status;

  HeartRateMeasurementResult({
    required this.heartRate,
    required this.measurementTime,
    required this.status,
  });
}

/// 心率数据模型
class HeartRateData {
  final DateTime date;
  final int heartRate;
  final int? sleepHeartRate;
  final int? awakeHeartRate;
  final List<int> hourlyData;
  final Map<String, int> zoneData;
  final HeartRateMeasurementResult? latestMeasurement;

  HeartRateData({
    required this.date,
    required this.heartRate,
    this.sleepHeartRate,
    this.awakeHeartRate,
    required this.hourlyData,
    required this.zoneData,
    this.latestMeasurement,
  });
}

/// 心率页面控制器
class HeartRateLogic extends GetxController {
  /// 戒指控制器
  late RingController _ringController;

  /// 获取戒指控制器
  RingController get ringController => _ringController;

  /// 当前时间范围
  final Rx<TimeRange> currentTimeRange = TimeRange.day.obs;

  /// 选中的时间索引
  final RxInt selectedTimeIndex = (-1).obs;

  /// 是否正在加载详细数据
  final RxBool isLoadingDetailedData = false.obs;

  /// 详细心率数据
  final RxList<int> detailedHeartRateData = <int>[].obs;

  /// 拖动线位置
  final RxDouble dragLineX = 0.0.obs;

  /// 模拟心率数据
  final Rx<HeartRateData?> heartRateData = Rx<HeartRateData?>(null);

  /// 是否正在测量心率
  final RxBool isMeasuring = false.obs;

  /// 当前测量结果
  final Rx<HeartRateMeasurementResult?> currentMeasurement =
      Rx<HeartRateMeasurementResult?>(null);

  /// API数据
  final Rx<api_models.HeartRateData?> apiHeartRateData =
      Rx<api_models.HeartRateData?>(null);
  final RxList<api_models.HeartRateRecord> heartRateList =
      <api_models.HeartRateRecord>[].obs;
  final RxBool isLoadingApiData = false.obs;

  /// 心率二级页API数据
  final Rxn<HeartRateAverageData> heartRateAverageData = Rxn<HeartRateAverageData>();
  final Rxn<SleepHeartRateData> sleepHeartRateData = Rxn<SleepHeartRateData>();
  final Rxn<SportHeartRateData> sportHeartRateData = Rxn<SportHeartRateData>();

  @override
  void onInit() {
    super.onInit();
    _ringController = Get.find<RingController>();
    _loadHeartRateData();
    _setupHeartRateMeasurementListener();
    _setupConnectionListener();
    // 延迟调用二级页接口
    Future.delayed(const Duration(milliseconds: 100), () {
      _fetchHeartRateSecondaryData();
    });
  }

  /// 设置连接状态监听器
  void _setupConnectionListener() {
    // 数据从API获取，不需要检查设备连接状态
    developer.log('📡 心率数据从API获取，无需检查设备连接', name: 'HeartRateController');
  }

  /// 设置心率测量监听器
  void _setupHeartRateMeasurementListener() {
    // 监听心率数据变化，当收到新的心率数据时自动上报
    // 由于心率数据不是Rx类型，我们需要定期检查
    _startHeartRateDataMonitor();
  }

  /// 处理测量完成
  Future<void> _handleMeasurementComplete() async {
    developer.log('🎯 开始处理测量完成', name: 'HeartRateController');

    // 获取最新的心率数据
    final heartRateData = _ringController.heartRateData;
    final currentHeartRate =
        heartRateData?.heartRate ?? _ringController.heartRate;

    developer.log('🎯 当前心率数据: $currentHeartRate', name: 'HeartRateController');

    if (currentHeartRate > 0) {
      developer.log('🎯 心率数据有效，开始处理', name: 'HeartRateController');

      // 创建测量结果
      final measurementResult = HeartRateMeasurementResult(
        heartRate: currentHeartRate,
        measurementTime: DateTime.now(),
        status: _getHeartRateStatus(currentHeartRate),
      );

      // 更新当前测量结果
      currentMeasurement.value = measurementResult;

      // 更新心率数据
      _updateHeartRateDataWithMeasurement(measurementResult);

      // 【移除上报逻辑】心率数据由RingService自动上报，不在这里上报
      
      // 刷新二级页数据
      _fetchHeartRateSecondaryData();

      // 显示测量完成提示
      Toast.show(
        '测量完成,心率: $currentHeartRate BPM',
      );
    } else {
      developer.log('❌ 心率数据无效: $currentHeartRate', name: 'HeartRateController');
    }
  }



  /// 获取心率状态
  String _getHeartRateStatus(int heartRate) {
    if (heartRate < 60) {
      return '偏低';
    } else if (heartRate <= 100) {
      return '正常';
    } else if (heartRate <= 120) {
      return '偏高';
    } else {
      return '过高';
    }
  }

  /// 更新心率数据（包含测量结果）
  void _updateHeartRateDataWithMeasurement(
      HeartRateMeasurementResult measurement) {
    final currentData = heartRateData.value;
    if (currentData != null) {
      heartRateData.value = HeartRateData(
        date: currentData.date,
        heartRate: measurement.heartRate, // 使用测量结果更新心率
        sleepHeartRate: currentData.sleepHeartRate,
        awakeHeartRate: currentData.awakeHeartRate,
        hourlyData: currentData.hourlyData,
        zoneData: currentData.zoneData,
        latestMeasurement: measurement,
      );
    }
  }

  /// 开始心率测量
  Future<void> startHeartRateMeasurement() async {
    developer.log('🚀 开始心率测量', name: 'HeartRateController');
    try {
      // 检查是否已经在测量中
      if (isMeasuring.value) {
        developer.log('⚠️ 已经在测量中，忽略重复请求', name: 'HeartRateController');
        return;
      }

      isMeasuring.value = true;
      developer.log('🚀 测量状态已设置为true', name: 'HeartRateController');

      await _ringController.startHeartRateMeasure();
      developer.log('🚀 戒指控制器心率测量已启动', name: 'HeartRateController');

      // 开始测量后，定期检查心率数据变化
      _startHeartRateDataCheck();
    } catch (e) {
      developer.log('❌ 开始心率测量失败: $e', name: 'HeartRateController');
      isMeasuring.value = false;
      Toast.show(
        '测量失败',
      );
    }
  }

  /// 停止心率测量
  Future<void> stopHeartRateMeasurement() async {
    developer.log('🛑 停止心率测量', name: 'HeartRateController');
    try {
      // 检查是否正在测量
      if (!isMeasuring.value) {
        developer.log('⚠️ 未在测量中，忽略停止请求', name: 'HeartRateController');
        return;
      }

      await _ringController.stopHeartRateMeasure();
      isMeasuring.value = false;

      // 停止测量后，处理测量结果
      _handleMeasurementComplete();
    } catch (e) {
      developer.log('❌ 停止心率测量失败: $e', name: 'HeartRateController');
      Toast.show(
        '停止失败',
      );
    }
  }

  /// 开始心率数据检查
  void _startHeartRateDataCheck() {
    int lastHeartRate = _ringController.heartRate;
    bool hasReported = false; // 标记是否已经上报过
    developer.log('🔍 开始心率数据检查，初始心率: $lastHeartRate', name: 'HeartRateController');

    // 每秒检查一次心率数据变化
    Timer.periodic(const Duration(seconds: 1), (timer) {
      if (!isMeasuring.value) {
        developer.log('🔍 测量已停止，取消定时器', name: 'HeartRateController');
        timer.cancel();
        return;
      }

      final currentHeartRate = _ringController.heartRate;
      developer.log(
          '🔍 检查心率数据: 上次=$lastHeartRate, 当前=$currentHeartRate, 测量状态=${_ringController.isHeartRateMeasuring}',
          name: 'HeartRateController');

      // 如果心率数据发生变化且大于0，且还没有上报过
      if (currentHeartRate != lastHeartRate && currentHeartRate > 0 && !hasReported) {
        developer.log('✅ 检测到心率数据变化，触发测量完成处理', name: 'HeartRateController');
        hasReported = true; // 标记已上报
        timer.cancel();
        isMeasuring.value = false;
        _handleMeasurementComplete();
      }

      lastHeartRate = currentHeartRate;

      // 如果测量状态已经停止，也停止检查
      if (!_ringController.isHeartRateMeasuring && !hasReported) {
        developer.log('🔍 测量状态已停止，触发测量完成处理', name: 'HeartRateController');
        hasReported = true; // 标记已上报
        timer.cancel();
        isMeasuring.value = false;
        _handleMeasurementComplete();
      }
    });
  }

  /// 开始心率数据监控（持续监听心率变化）
  void _startHeartRateDataMonitor() {
    // 移除持续监控和自动上报逻辑
    // 只在用户主动测量时才上报数据
    developer.log('📡 心率数据监控已禁用，仅在主动测量时上报', name: 'HeartRateController');
  }

  /// 设置时间范围
  void setTimeRange(TimeRange timeRange) {
    currentTimeRange.value = timeRange;
    selectedTimeIndex.value = -1;
    _loadHeartRateData();
    // 切换时间范围时重新获取数据
    _fetchHeartRateSecondaryData();
  }

  /// 加载心率数据
  void _loadHeartRateData() {
    // 模拟心率数据
    final now = DateTime.now();
    final hourlyData = List.generate(48, (index) {
      // 模拟24小时的心率数据，每30分钟一个数据点
      final hour = index * 0.5;
      if (hour >= 22 || hour <= 6) {
        // 睡眠时间，心率较低
        return 55 + (index % 10);
      } else if (hour >= 7 && hour <= 9) {
        // 早晨，心率稍高
        return 65 + (index % 15);
      } else if (hour >= 12 && hour <= 14) {
        // 中午，可能有活动
        return 70 + (index % 20);
      } else if (hour >= 18 && hour <= 20) {
        // 傍晚，可能有运动
        return 75 + (index % 25);
      } else {
        // 其他时间
        return 60 + (index % 15);
      }
    });

    final zoneData = {
      '热身放松': 120, // 分钟
      '脂肪燃烧': 45,
      '心肺强化': 30,
      '耐力强化': 15,
      '无氧极限': 5,
    };

    // 获取最新的测量结果
    final latestMeasurement = currentMeasurement.value;

    heartRateData.value = HeartRateData(
      date: now,
      heartRate: latestMeasurement?.heartRate ?? 62, // 如果有测量结果则使用，否则使用默认值
      sleepHeartRate: 58,
      awakeHeartRate: 72,
      hourlyData: hourlyData,
      zoneData: zoneData,
      latestMeasurement: latestMeasurement,
    );

    // 加载详细数据
    if (currentTimeRange.value == TimeRange.day) {
      detailedHeartRateData.value = hourlyData;
    }
  }

  /// 获取心率列表
  Future<void> getHeartRateList() async {
    try {
      isLoadingApiData.value = true;

      final deviceSn = _ringController.connectedDevice?.deviceSn;
      if (deviceSn == null) {
        Toast.show(
          '设备未连接',
        );
        return;
      }

      final response = await DefaultApi().queryHeartRateListGet<List<dynamic>>(
        deviceSn: deviceSn,
        isShowErrMsg: false,
        isShowLoading: false,
      );
      if (response != null) {
        // 将 List<dynamic> 转换为 List<HeartRateRecord>
        final heartRateRecords = response.map((item) {
          if (item is Map<String, dynamic>) {
            return api_models.HeartRateRecord.fromJson(item);
          } else {
            throw Exception('无效的心率记录数据格式');
          }
        }).toList();

        heartRateList.value = heartRateRecords;
        developer.log('✅ 心率列表获取成功，共 ${heartRateRecords.length} 条记录');
      } else {
        heartRateList.clear();
        Toast.show('没有获取到心率数据');
      }
    } catch (e) {
      print('获取心率列表失败: $e');
      Toast.show(
        '获取心率列表时发生错误: $e',
      );
    } finally {
      isLoadingApiData.value = false;
    }
  }

  /// 手动刷新心率列表数据并上报
  Future<void> refreshHeartRateListData() async {
    try {
      developer.log('🔄 手动刷新心率列表数据', name: 'HeartRateController');

      // 显示加载状态
      Toast.show('正在获取心率数据...');

      // 重新获取二级页数据
      await _fetchHeartRateSecondaryData();

      developer.log('✅ 心率数据刷新完成', name: 'HeartRateController');
      Toast.show('心率数据已更新');
    } catch (e) {
      developer.log('❌ 手动刷新心率列表数据失败: $e', name: 'HeartRateController');
      Toast.show('获取心率数据时发生错误: $e');
    }
  }

  /// 获取指定日期的心率详情
  Future<List<api_models.HeartRateRecord>> getHeartRateDetail(
      String dailyValue) async {
    try {
      final deviceSn = _ringController.connectedDevice?.deviceSn;
      if (deviceSn == null) {
        throw Exception('设备未连接');
      }

      final response = await DefaultApi().queryHeartRateListGet<List<dynamic>>(
        deviceSn: deviceSn,
        dailyValue: dailyValue,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      if (response != null) {
        return response.map((item) {
          if (item is Map<String, dynamic>) {
            return api_models.HeartRateRecord.fromJson(item);
          } else {
            throw Exception('无效的心率记录数据格式');
          }
        }).toList();
      } else {
        throw Exception('获取数据失败');
      }
    } catch (e) {
      print('获取心率详情失败: $e');
      rethrow;
    }
  }

  /// 刷新详细数据
  void refreshDetailedData() {
    isLoadingDetailedData.value = true;

    // 模拟网络请求延迟
    Future.delayed(const Duration(seconds: 2), () {
      isLoadingDetailedData.value = false;
      _loadHeartRateData();
    });
  }

  /// 显示日历选择器
  void showCalendarPicker() async {
    final selectedDate = await Get.to(() => const SimpleCalendarView(
      calendarType: CalendarType.heartRate,
    ));
    if (selectedDate != null && selectedDate is String) {
      loadDataByDate(selectedDate);
    }
  }

  /// 处理图表拖动更新
  void handleChartPanUpdate(double dx, double barWidth, int dataLength) {
    final hour = (dx / barWidth).floor();
    if (hour >= 0 && hour < 24) {
      // 优先使用API数据
      final apiData = heartRateAverageData.value;
      if (apiData != null) {
        // 查找该小时对应的数据点
        final automaticInfoVOS = apiData.automaticInfoVOS;
        for (int i = 0; i < automaticInfoVOS.length; i++) {
          final info = automaticInfoVOS[i];
          final timeParts = info.code.split(':');
          final dataHour = int.parse(timeParts[0]);
          
          if (dataHour == hour && info.value > 0) {
            selectedTimeIndex.value = i;
            dragLineX.value = dx;
            break;
          }
        }
      } else {
        // 回退到历史数据
        final historyHeartRateData = _ringController.historyHeartRateData;
        if (historyHeartRateData != null) {
          // 计算该小时对应的数据索引范围
          final timeInterval = historyHeartRateData.timeInterval;
          final startIndex = (hour * 60) ~/ timeInterval;
          final endIndex = ((hour + 1) * 60) ~/ timeInterval;

          // 在该小时内查找有效的心率数据
          for (int i = startIndex;
              i < endIndex && i < historyHeartRateData.heartRateList.length;
              i++) {
            final heartRate = historyHeartRateData.heartRateList[i];
            if (heartRate != null && heartRate > 0) {
              selectedTimeIndex.value = i;
              dragLineX.value = dx;
              break;
            }
          }
        } else {
          selectedTimeIndex.value = hour;
          dragLineX.value = dx;
        }
      }
    }
  }

  /// 处理图表拖动结束
  void handleChartPanEnd() {
    dragLineX.value = 0.0;
  }

  /// 处理图表点击
  void handleChartTapUp(double dx, double barWidth, int dataLength) {
    final hour = (dx / barWidth).floor();
    if (hour >= 0 && hour < 24) {
      // 优先使用API数据
      final apiData = heartRateAverageData.value;
      if (apiData != null) {
        // 查找该小时对应的数据点
        final automaticInfoVOS = apiData.automaticInfoVOS;
        for (int i = 0; i < automaticInfoVOS.length; i++) {
          final info = automaticInfoVOS[i];
          final timeParts = info.code.split(':');
          final dataHour = int.parse(timeParts[0]);
          
          if (dataHour == hour && info.value > 0) {
            selectedTimeIndex.value = i;
            break;
          }
        }
      } else {
        // 回退到历史数据
        final historyHeartRateData = _ringController.historyHeartRateData;
        if (historyHeartRateData != null) {
          // 计算该小时对应的数据索引范围
          final timeInterval = historyHeartRateData.timeInterval;
          final startIndex = (hour * 60) ~/ timeInterval;
          final endIndex = ((hour + 1) * 60) ~/ timeInterval;

          // 在该小时内查找有效的心率数据
          for (int i = startIndex;
              i < endIndex && i < historyHeartRateData.heartRateList.length;
              i++) {
            final heartRate = historyHeartRateData.heartRateList[i];
            if (heartRate != null && heartRate > 0) {
              selectedTimeIndex.value = i;
              break;
            }
          }
        } else {
          selectedTimeIndex.value = hour;
        }
      }
    }
  }

  /// 获取总时长
  String getTotalDuration() {
    final data = heartRateData.value;
    if (data == null) return '-- 小时 -- 分钟';

    final totalMinutes =
        data.zoneData.values.fold<int>(0, (sum, minutes) => sum + minutes);
    final hours = totalMinutes ~/ 60;
    final minutes = totalMinutes % 60;

    return '$hours 小时 $minutes 分钟';
  }

  /// 获取日期标题（根据时间范围使用不同字段）
  String getDateTitle() {
    final heartRateAverageData = this.heartRateAverageData.value;
    
    if (heartRateAverageData != null) {
      // 周和月视图使用 dateStart 和 dateEnd
      if (currentTimeRange.value == TimeRange.week ||
          currentTimeRange.value == TimeRange.month) {
        if (heartRateAverageData.dateStart != null && heartRateAverageData.dateEnd != null) {
          return '${heartRateAverageData.dateStart} - ${heartRateAverageData.dateEnd}';
        }
      }
      
      // 日视图使用 recordDate 和 weekName
      if (currentTimeRange.value == TimeRange.day &&
          heartRateAverageData.recordDate.isNotEmpty) {
        final endTime = heartRateAverageData.endTime ?? '00:00';
        return '${heartRateAverageData.recordDate}，${heartRateAverageData.weekName}，$endTime 平均';
      }
    }

    // 降级方案：使用当前日期
    final d = DateTime.now();
    const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    final weekday = weekdays[(d.weekday - 1).clamp(0, 6)];
    return '${d.year}年${d.month.toString().padLeft(2, '0')}月${d.day.toString().padLeft(2, '0')}日，$weekday，00:00 平均';
  }

  /// 获取测量时间格式化字符串
  String getMeasurementTimeString() {
    final measurement = currentMeasurement.value;
    if (measurement == null) return '';

    final time = measurement.measurementTime;
    return '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
  }

  /// 获取测量日期格式化字符串
  String getMeasurementDateString() {
    final measurement = currentMeasurement.value;
    if (measurement == null) return '';

    final time = measurement.measurementTime;
    return '${time.year}/${time.month.toString().padLeft(2, '0')}/${time.day.toString().padLeft(2, '0')}';
  }

  /// 获取心率二级页数据
  Future<void> _fetchHeartRateSecondaryData() async {
    try {
      developer.log('📊 开始获取心率二级页数据...', name: 'HeartRateController');

      // 获取设备序列号
      final deviceSnManager = Get.find<DeviceSnManager>();
      final deviceSn = deviceSnManager.getDeviceSn();
      
      if (deviceSn.isEmpty) {
        developer.log('⚠️ 设备SN为空，无法获取心率数据', name: 'HeartRateController');
        return;
      }

      // 获取当前日期
      final now = DateTime.now();
      final recordDate =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

      developer.log('📅 设备序列号: $deviceSn, 日期: $recordDate',
          name: 'HeartRateController');

      // 并行调用三个心率相关接口
      await Future.wait([
        _fetchHeartRateAverage(deviceSn, recordDate),
        _fetchSportHeartRate(deviceSn, recordDate),
        _fetchSleepHeartRateSecond(deviceSn, recordDate),
      ]);

      developer.log('✅ 心率二级页数据获取完成', name: 'HeartRateController');
    } catch (e) {
      developer.log('❌ 获取心率二级页数据异常: $e', name: 'HeartRateController');
    }
  }

  /// 获取当前时间范围对应的type值
  String _getTypeFromTimeRange() {
    switch (currentTimeRange.value) {
      case TimeRange.day:
        return '1';
      case TimeRange.week:
        return '2';
      case TimeRange.month:
        return '3';
    }
  }

  /// 获取心率平均值
  Future<void> _fetchHeartRateAverage(
      String deviceSn, String recordDate) async {
    try {
      final response = await DefaultApi().queryHeartRateAverageGet(
        deviceSn: deviceSn,
        recordDate: recordDate,
        type: _getTypeFromTimeRange(),
        isShowErrMsg: false,
        isShowLoading: false,
      );
      
      // 解析数据
      if (response != null && response['data'] != null) {
        heartRateAverageData.value = HeartRateAverageData.fromJson(response['data']);
        developer.log('✅ 心率平均值数据解析成功', name: 'HeartRateController');
      }
    } catch (e) {
      developer.log('❌ 获取心率平均值失败: $e', name: 'HeartRateController');
    }
  }

  /// 获取运动期间心率
  Future<void> _fetchSportHeartRate(String deviceSn, String recordDate) async {
    try {
      final response = await DefaultApi().querySportHeartRateGet(
        deviceSn: deviceSn,
        recordDate: recordDate,
        type: _getTypeFromTimeRange(),
        isShowErrMsg: false,
        isShowLoading: false,
      );
      developer.log('✅ 运动期间心率获取成功: $response', name: 'HeartRateController');
      
      // 解析数据
      if (response != null && response['data'] != null) {
        sportHeartRateData.value = SportHeartRateData.fromJson(response['data']);
        developer.log('✅ 运动期间心率数据解析成功', name: 'HeartRateController');
      }
    } catch (e) {
      developer.log('❌ 获取运动期间心率失败: $e', name: 'HeartRateController');
    }
  }

  /// 获取平均睡眠心率
  Future<void> _fetchSleepHeartRateSecond(
      String deviceSn, String recordDate) async {
    try {
      final response = await DefaultApi().querySleepHeartRateSecondGet(
        deviceSn: deviceSn,
        recordDate: recordDate,
        type: _getTypeFromTimeRange(),
        isShowErrMsg: false,
        isShowLoading: false,
      );
      developer.log('✅ 平均睡眠心率获取成功: $response', name: 'HeartRateController');
      
      // 解析数据
      if (response != null && response['data'] != null) {
        sleepHeartRateData.value = SleepHeartRateData.fromJson(response['data']);
        developer.log('✅ 平均睡眠心率数据解析成功', name: 'HeartRateController');
      }
    } catch (e) {
      developer.log('❌ 获取平均睡眠心率失败: $e', name: 'HeartRateController');
    }
  }

  /// 根据指定日期加载数据
  void loadDataByDate(String recordDate) {
    developer.log('📅 根据日期加载心率数据: $recordDate', name: 'HeartRateController');
    
    // 获取设备SN
    final deviceSnManager = Get.find<DeviceSnManager>();
    final deviceSn = deviceSnManager.getDeviceSn();

    if (deviceSn.isEmpty) {
      developer.log('⚠️ 设备SN为空，无法获取心率数据', name: 'HeartRateController');
      return;
    }

    // 并行调用三个心率相关接口
    Future.wait([
      _fetchHeartRateAverage(deviceSn, recordDate),
      _fetchSportHeartRate(deviceSn, recordDate),
      _fetchSleepHeartRateSecond(deviceSn, recordDate),
    ]);
  }
}
